//
//  AdvView.m
//  tujiaoipad
//
//  Created by admin on 12-7-22.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "AdvView.h"
#import "CommonConfigUtil.h"



@implementation AdvView

@synthesize advDelegate;
@synthesize advList;


- (id)initWithFrame:(CGRect)frame aList:(NSMutableArray*)aList
{
    if (self = [super initWithFrame:frame]) {
      
       

        UIInterfaceOrientation t_orientation=[[UIApplication sharedApplication] statusBarOrientation ];
        
        if(t_orientation==UIInterfaceOrientationLandscapeLeft||t_orientation==UIInterfaceOrientationLandscapeRight){
            landScape=YES;
            
        }else{
            
            landScape=NO;
        }
        

        self.advList=aList;

        advScrollView=[[UIScrollView alloc] init];
        advScrollView.showsVerticalScrollIndicator=NO;
        advScrollView.showsHorizontalScrollIndicator=NO;
        advScrollView.pagingEnabled=YES;
        advScrollView.delegate=self;
        advScrollView.delaysContentTouches=YES;
        advScrollView.canCancelContentTouches=NO;
        advScrollView.frame=CGRectMake(0, 0, frame.size.width, frame.size.height);
        [self addSubview:advScrollView];
        
        [self addAdv];
        //[self addObserver];
        
        //定时移动广告位
        if([self.advList count]>1){
            theTime=[NSTimer scheduledTimerWithTimeInterval:6 target:self selector:@selector(scrollAdv) userInfo:nil repeats:YES];
        }
        
        
    }
    return self;
}

-(void)resetdAdvList:(NSMutableArray*)adDataList
{
    self.advList=adDataList;


 
    for (UIView *subview in [advScrollView subviews]) {
        if([subview isKindOfClass:[UIImageView class]]){
            ((UIImageView *)subview).image=nil;
        }
        [subview removeFromSuperview];
    }
    
    for (UIView *subview in [self subviews]) {
        if([subview isKindOfClass:[UIImageView class]]){
            ((UIImageView *)subview).image=nil;
            [subview removeFromSuperview];
        }
        
    }
   
    [self addAdv];
    

}


//更新图片
- (void)updateImageToScrollView:(NSString *)index 
{ 
	  
    NSString *imageUrl= [[self.advList objectAtIndex:[index intValue]] objectForKey:@"image"] ;
    
    NSString  *adv_image_local =[[self.advList objectAtIndex:[index intValue]] objectForKey:@"adv_image_local"] ;
    
    BOOL status=[CommonConfigUtil writeImage:imageUrl toImagePath:adv_image_local];
    if(status==YES){	
        [self performSelectorOnMainThread:@selector(setImage:) withObject:index waitUntilDone:NO];
    }
    else{
        // NSLog(@"fail: prodId:%@,smallPhoto_netPath:%@",prodId,smallPhoto_netPath);
    }
    
    
    
    
} 

//设置图片
-(void)setImage:(NSString*)index {
    NSString *adv_image_local= [[self.advList objectAtIndex:[index intValue]] objectForKey:@"adv_image_local"] ;
    if(nil!=adv_image_local&&![@"" isEqualToString:adv_image_local]){
        UIButton *imageShowBut=(UIButton*)[advScrollView viewWithTag:40+[index intValue] ];
        if(nil!=imageShowBut){
        UIImage *image=[[UIImage alloc] initWithContentsOfFile:adv_image_local];
        if(nil!=image){
            [imageShowBut setBackgroundImage:image forState:UIControlStateNormal];
        }
         
        }    
       
    }
    
    
}


-(void)imageOnClickAction:(id)sender{
    int indexRow=((UIButton *)sender).tag-40;
    if(nil!=self.advList && indexRow>=0 && indexRow<[self.advList count]){
        NSString *advid=[[self.advList objectAtIndex:indexRow] objectForKey:@"advid" ];
        NSString *advtype=[[self.advList objectAtIndex:indexRow] objectForKey:@"advtype" ];
        NSString *name=[[self.advList objectAtIndex:indexRow] objectForKey:@"name" ];
        NSString *objectId=[[self.advList objectAtIndex:indexRow] objectForKey:@"objectId" ];
        NSString *objectName=[[self.advList objectAtIndex:indexRow] objectForKey:@"objectName" ];
        NSString *urlparams=[[self.advList objectAtIndex:indexRow] objectForKey:@"urlparams" ];
        
        if(nil==advtype)return;
        if(nil==advid)advid=@"";
        if(nil==name)name=@"";
        if(nil==objectId)objectId=@"";
        if(nil==objectName)objectName=@"";
        if(nil==urlparams)urlparams=@""; 
        
   
        NSDictionary *params=[NSDictionary dictionaryWithObjectsAndKeys:advid,@"advid",advtype,@"advtype",name,@"name",objectId,@"objectId",objectName,@"objectName",urlparams,@"urlparams",nil];
        
        
        if ([self.advDelegate respondsToSelector:@selector(advSelectWithParams:)]) {
            [self.advDelegate advSelectWithParams:params];
        }
        
        
    }
    
    
    
   
}






//增加广告位内容
-(void)addAdv{
   
    if(nil!=self.advList&&[self.advList count]>0){
        advScrollView.contentSize=CGSizeMake(advScrollView.frame.size.width*[self.advList count], advScrollView.frame.size.height);
    }
    else{
        advScrollView.contentSize=CGSizeMake(advScrollView.frame.size.width, advScrollView.frame.size.height);
    }   
   
    
    currentPage=0;//当前页为0
    
    if(nil!=self.advList&&[self.advList count]>0){
        CGRect frame;
        for(int i=0;i<[self.advList count];i++){
            frame=CGRectMake(advScrollView.frame.size.width*i, advScrollView.frame.origin.y, advScrollView.frame.size.width, advScrollView.frame.size.height);
            
            UIButton *imageShowBut= [UIButton buttonWithType:UIButtonTypeCustom]   ;
            imageShowBut.frame=frame;
            imageShowBut.backgroundColor=[UIColor clearColor];
            imageShowBut.tag= 40+i;    
            [imageShowBut addTarget:self action:@selector(imageOnClickAction:)  forControlEvents:UIControlEventTouchUpInside];
            
            NSString *adv_image_local= [[self.advList objectAtIndex:i] objectForKey:@"adv_image_local"] ;
            if(nil==adv_image_local) adv_image_local=@"";
            
            if([CommonConfigUtil existImageWithLocalPath:adv_image_local]){
                UIImage *image=[[UIImage alloc] initWithContentsOfFile:adv_image_local];
                if(nil!=image){
                    [imageShowBut setBackgroundImage:image forState:UIControlStateNormal];
                }
                
              
            }
            
            else {
                [NSThread detachNewThreadSelector:@selector(updateImageToScrollView:) toTarget:self withObject:[NSString stringWithFormat:@"%i",i]]; 
            }
            
            [advScrollView addSubview:imageShowBut];
            
            
            //增加页码标签
            if([self.advList count]>1){
                frame=CGRectMake(advScrollView.frame.size.width-20*([self.advList count]-i),advScrollView.frame.size.height-15, 10, 10);
                UIImageView *imageView = [[UIImageView alloc] initWithFrame:frame];
                if(i==currentPage){
                    imageView.image=[UIImage imageNamed:@"active_page_spot.png"];    
                }else{
                    imageView.image=[UIImage imageNamed:@"inactive_page_spot.png"];
                }    
                imageView.tag= 60+i;
                [self addSubview:imageView];
                
            }
            
        }
        
        
        
    }
   
    
}


//定时移动广告位
- (void)scrollAdv{
    
    // NSLog(@"scrollAdv");
    
    //如果是最后一页，则移动到第一页
    if(currentPage==[self.advList count]-1){
        currentPage=0;
    }else{
        currentPage=currentPage+1;
    }
    
    CGRect frame=CGRectMake(advScrollView.frame.size.width*currentPage, advScrollView.frame.origin.y, advScrollView.frame.size.width, advScrollView.frame.size.height);
    
    [advScrollView scrollRectToVisible:frame animated:YES]; 
    
    
}


//设置当前页码标签
-(void)setActivePageSpot{
    for(int i=0;i<[self.advList count];i++){
        UIImageView *imageView=(UIImageView*)[self viewWithTag:60+i];
        if(i==currentPage){
            imageView.image=[UIImage imageNamed:@"active_page_spot.png"];    
        }else{
            imageView.image=[UIImage imageNamed:@"inactive_page_spot.png"];
        } 
    }
}




-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    // NSLog(@"scrollViewWillBeginDragging");
    if([self.advList count]>1 && nil!=theTime){
        [theTime invalidate];
        theTime=nil;   
    }    
    
    
}


//广告栏移动
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat pageWidth=scrollView.frame.size.width;
    int page=floor((scrollView.contentOffset.x-pageWidth/[self.advList count])/pageWidth)+1;
    if(page<[self.advList count]){
        currentPage=page;
    }  
    [self setActivePageSpot];
    
}


-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    // NSLog(@"scrollViewDidEndDecelerating");
    //定时移动广告位
    if([self.advList count]>1&& nil==theTime){
        theTime=[NSTimer scheduledTimerWithTimeInterval:6 target:self selector:@selector(scrollAdv) userInfo:nil repeats:YES];
    }    
}



/*
- (void)addObserver
{
	[[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector(deviceOrientationDidChange)
												 name:@"UIDeviceOrientationDidChangeNotification" object:nil];
}


- (void)deviceOrientationDidChange
{
   
        [self reloadAdvViewFrame];
	
}
*/

-(void)reloadAdvViewFrame{
    
     advScrollView.frame=CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
    
    
    if(nil!=advList&&[self.advList count]>0){
        advScrollView.contentSize=CGSizeMake(advScrollView.frame.size.width*[self.advList count], advScrollView.frame.size.height);
        
        
        for(int i=0;i<[self.advList count];i++){
            
            UIButton *imageShowBut=(UIButton *)[advScrollView viewWithTag:40+i];
            if(nil!=imageShowBut) 
            {
          CGRect frame=CGRectMake(advScrollView.frame.size.width*i, advScrollView.frame.origin.y, advScrollView.frame.size.width, advScrollView.frame.size.height);
           imageShowBut.frame=frame;
            }
            
            if([self.advList count]>1){
            UIImageView *imageView =(UIImageView *)[self viewWithTag:60+i];
            if(nil!=imageView){
             CGRect frame=CGRectMake(advScrollView.frame.size.width-20*([self.advList count]-i),advScrollView.frame.size.height-15, 10, 10);
                imageView.frame=frame;
            }
            }
           
            
           
        }  
    }
    else{
        advScrollView.contentSize=CGSizeMake(advScrollView.frame.size.width, advScrollView.frame.size.height);
    }   
    
    
}

/***************************广告处理 end***************************************/


-(void)dealloc
{
    
}

@end
